package com.mattgarner.jaddas.util;

import java.util.ArrayList;
import java.util.HashMap;

public class MRUCache<K, V> {

	// Implements a Most Recently Used Cache by MJG.
	// implements a HashMap that will not expand past a certain
	// size. It prunes the least recently accessed key off when
	// the size exceeds the limit.
	private int _size;
	private HashMap<K, V> _map;
	private ArrayList<K> _order;

	// default constructor
	public MRUCache() {
		this(10);
	}

	// constructor
	public MRUCache(int size) {
		_size = size;
		_map = new HashMap<K, V>(size + 1); //(size + 1, 1.00f);
		_order = new ArrayList<K>(size);
	}

	public final synchronized void put(K key, V value) {
		_map.put(key, value);
		updatePosition(key);
		this.prune();
	}

	private final synchronized void updatePosition(K key) {
		_order.remove(key);
		_order.add(0, key);
	}

	private final synchronized void prune() {
		for (int a = _size; a < _order.size(); a++) {
			K key = _order.get(a);
			this.remove(key);
		}
	}

	public final synchronized V get(K key) {
		this.updatePosition(key);
		return _map.get(key);
	}

	public final synchronized void remove(K key) {
		_map.remove(key);
		_order.remove(key);
	}

	public final synchronized void clear() {
		_map.clear();
		_order.clear();
	}

}